package com.hejing.object类.Object类之equals方法;

import java.util.Objects;

/**
 * ClassName: User
 * Package: com.hejing.object类.Object类之equals方法
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-03-26 21:21
 * @Version: 1.0
 */
public class User {
    String name;
    int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 方式1: 手动重写Object中的equals() 方法:
    /*@Override
    public boolean equals(Object obj) {
        if(this == obj) {  // 如果是同一块地址，返回true
            return true;
        }
        if(obj instanceof User) {
            User user = (User)obj;
            if(this.age == user.age && this.name.equals(user.name)) {
                return true;
            }
        }
        return false;
    }*/

    // 方式2: idea-generate自动实现
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age && Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

























